// 导入依赖的模块
yepjs.require("jquery");
yepjs.require("YBA.Common");
yepjs.require("YBA.Plugin.plugins");
yepjs.require("YBA.Plugin.wdatePicker");
yepjs.require("YBA.Data.Admin");

// 后台管理 - 云存储列表管理
yepjs.define("list", {

    NS: "YBA.Logic.Admin",

    field: function() {

        var Biz = {
            // 初始化事件
            init: function() {

                Biz.fn.getStorageCloudList(function (json) {

                    // 设置初始列表项目的数量，创建分页控件需要使用该数量
                    Biz.vars.totalNum = json.page.totalRecord;

                    for (var i in Biz.event) {
                        Biz.event[i]();
                    }
                });
            },
            //  公共变量
            vars: {
                // 模板列表
                tpl: (function(){
                    var tpl = {};
                    $("script[type='text/ysmart']").each(function(){
                        var t = $(this);
                        tpl[t.attr("data-name")] = t.html();
                    });
                    return tpl;
                })(),
                // 报表搜索字段
                searchVar: {
                    name: "",          // 云存储名称  string  可选
                    startPos: 1,          // 当前页  int  必填
                    pageSize: 18          // 页面大小  int  必填
                },
                // 列表项目的总数量
                totalNum: 0,
                // 分页控件引用
                pageCtrl: null
            },
            // 页面元素
            el: {
                body: $("body"),
                jcloudName: $("#j-cloudName"),
                jpage: $("#j-page"),
                jlist: $("#j-list"),
                jaddStorageCloud: $("#j-addStorageCloud"),
                jdeleteStorageCloud:$("#j-deleteStorageCloud"),
                jallObj:$(".j-checkAll"),
                jtotalNum: $("#j-totalNum")
            },
            // 功能函数集合
            fn: {
                // 读取终端列表
            	getStorageCloudList: function (callback) {
                    YBA.Data.Admin.getStorageCloudList(Biz.vars.searchVar, function (json) {
                        if(json.code == 200) {
                            Biz.el.jlist.html(YBA.Common.ysmart(Biz.vars.tpl.list, json.list));
                            Biz.el.jtotalNum.html(json.page.totalRecord);

                            Biz.vars.pageCtrl && Biz.vars.pageCtrl.setTotalNum(json.page.totalRecord);

                            callback && callback(json);
                        }else{
                            YBA.Plugin.msgtip({type: "i", msg: json.desc})
                        }
                    });
                },
                // 表单验证
                formCheck: function(form,name) {

                	// 显示错误信息
                    var showError = function(obj, msg) {
                        var msgDom = obj.siblings('.message');
                        var msgTxt = msgDom.children('i')
                        msgDom.addClass("msg-error").removeClass('msg-tip');
                        msgTxt.html(msg);
                        msgDom.show();
                    };

                    // 隐藏错误信息
                    var hideError = function(obj, msg) {
                        var msgDom = obj.siblings('.message');
                        var msgTxt = msgDom.children('i')
                        msgDom.hide();
                        msgDom.addClass("msg-tip").removeClass('msg-error');
                        msgTxt.html(msg);
                    };

                    // 数据验证对象
                    var dataCheck = {
                        name:{
                            obj: form.find("[name='name']"),
                            fn: function() {
                                var val = this.obj.val();
                                if (YBA.Common.check.isNull(val)) {
                                    showError(this.obj,"请输入云存储名称");
                                    return false;
                                } else if(YBA.Common.check.isHowLong(val,255)){
                                	showError(this.obj,"云存储名称过长");
                                    return false;
                                } else {
                                    hideError(this.obj,"请输入云存储名称");
                                    return true;
                                }
                            }
                        },
                        spaceCapacity: {
                            obj: form.find("[name='spaceCapacity']"),
                            fn: function() {
                                var val = this.obj.val();
                                if (YBA.Common.check.isNull(val)) {
                                    showError(this.obj,"请输入云存储总空间");
                                    return false;
                                } else if(!YBA.Common.check.isNum(val,{"min":1,"decimals":0})){
                                	showError(this.obj,"请输入正整数");
                                    return false;
                                } else if(YBA.Common.check.isHowLong(val,20)){
                                	showError(this.obj,"云存储总空间过大");
                                    return false;
                                } else {
                                    hideError(this.obj,"请输入云存储总空间");
                                    return true;
                                }
                            }
                        },
                        spaceUsage: {
                            obj: form.find("[name='spaceUsage']"),
                            fn: function() {
                                var val = this.obj.val();
                                if (YBA.Common.check.isNull(val)) {
                                    showError(this.obj,"请输入已用空间");
                                    return false;
                                } else if(!YBA.Common.check.isNum(val,{"min":0})){
                                	showError(this.obj,"请输入非负数");
                                    return false;
                                } else if(parseFloat(val) > parseFloat(dataCheck["spaceCapacity"].obj.val())){
                                    showError(this.obj,"已用空间超过总空间");
                                    return false;
                                } else if(YBA.Common.check.isHowLong(val,20)){
                                	showError(this.obj,"已用空间过大");
                                    return false;
                                } else {
                                    hideError(this.obj,"请输入已用空间");
                                    return true;
                                }
                            }
                        }
                    };

                    if (name && dataCheck[name]) {
                        return dataCheck[name].fn();
                    } else {
                        var errLen = 0;
                        for (var i in dataCheck) {
                            if (!dataCheck[i].fn()) {
                                errLen++;
                            }
                        }
                        if (errLen > 0) {
                            return false;
                        }
                        return true;
                    }
                },
                // 云存储通知新增或修改弹窗
                storageCloudForm: function(data){

                    var popform = new YBA.Plugin.popform({
                        title: (!(data))?"新增云存储":"修改云存储",
                        className: "ui-dialog-storageCloud",
                        content: YBA.Common.ysmart(Biz.vars.tpl.storageCloudTpl, data || {} ),
                        width: 564,
                        destroy: true,
                        onHide: function () {
                            // 隐藏弹窗时要执行的回调函数
                        },
                        onShow: function () {
                            // 显示弹窗时要执行的回调函数
                            var op = $(".form-group");
                            var form = $(".ui-dialog-form");
                            op.each(function() {
                                var t = $(this),
                                    input = t.find(".required"),
                                    name = input.attr("name"),
                                    holder = input.siblings(".message");
                                input.blur(function() {
                                    Biz.fn.formCheck(form,name);
                                }).focus(function() {
                                    holder.show();
                                });;
                            });
                        },
                        btns: [{
                            value: "确定",
                            className: "blue btn g-mr10",
                            fn: function () {
                                var form = $(".ui-dialog-form");
                                if (!Biz.fn.formCheck(form)) {
                                    return false;
                                }else{
                                    var form = popform.self.find("form");
                                    var data = form.serialize();
                                    var dataId = $("#j-dataId").val();
                                    var callbackFn = function(json){
                                        if(json.code == 200) {
                                            YBA.Plugin.msgtip({type: "o", msg: json.desc});
                                            popform.hide();
                                            Biz.fn.getStorageCloudList();
                                        }else{
                                            YBA.Plugin.msgtip({type: "i", msg: json.desc});
                                        }
                                    }
                                    if(!dataId){
                                        YBA.Data.Admin.addStorageCloud(data, callbackFn);
                                    }else{
                                        YBA.Data.Admin.updateStorageCloud(data, callbackFn);
                                    }
                                }
                            }
                        }, {
                            value: "取消",
                            className: "red btn g-ml10",
                            fn: function () {
                                popform.hide();
                            }
                        }]
                    }).show();

                    return false;
                },
                // 获取云存储详情
                getStorageCloudDetail: function(id, callback){
                    YBA.Data.Admin.getStorageCloudDetail({id: id}, function(json){
                        if(json.code == 200) {
                            callback && callback(json.obj);
                        }else{
                            YBA.Plugin.msgtip({type: "i", msg: json.desc})
                        }
                    })
                },
                //删除云存储
                deleteStorageCloud:function(data){
                    var confirm = YBA.Plugin.confirm({
                        msg: "您确定要删除这些云存储吗？",
                        btnTxt1: "确定",
                        yes: function () {
                            confirm.hide();
                            YBA.Data.Admin.deleteStorageCloud(data, function (json) {
                                if(json.code == 200){
                                    YBA.Plugin.msgtip({type: "o", msg: "操作成功"});
                                    Biz.vars.searchVar.startPos = 1;
                                    Biz.vars.pageCtrl.setPageIndex(1);
                                    Biz.el.jallObj.prop("checked", false);
                                    Biz.fn.getStorageCloudList();
                                }else{
                                    YBA.Plugin.msgtip({type: "i", msg: "操作失败"});
                                }
                            })
                        }
                    })
                }
            },
            // 初始化时执行的所有事件
            event: {
                // 搜索
                search: function () {
                    // 点击“查询”时，设置搜索条件
                    Biz.el.body.delegate(".j-search", "click", function () {
                        Biz.vars.searchVar.name = Biz.el.jcloudName.val();
                        Biz.vars.searchVar.startPos = 1;

                        Biz.vars.pageCtrl.setPageIndex(1);

                        Biz.fn.getStorageCloudList();
                    });

                    // 点击“重置”时，重置搜索条件
                    Biz.el.body.delegate(".j-reset", "click", function () {

                        Biz.el.jcloudName.val("");

                        Biz.vars.searchVar.name = "";
                        Biz.vars.searchVar.startPos = 1;

                        Biz.vars.pageCtrl.setPageIndex(1);

                        Biz.fn.getStorageCloudList();
                    });
                },
                // 分页
                pageNav: function () {
                    // 创建分页控件
                    Biz.vars.pageCtrl = new YBA.Plugin.pageNav({
                        // 放置分页控件的容器
                        pageCon: Biz.el.jpage,
                        // 每页数量
                        pageSize: Biz.vars.searchVar.pageSize,
                        // 总数量
                        totalNum: Biz.vars.totalNum,
                        // 回调函数
                        callback: function (pageIndex) {
                            // 设置页次
                            Biz.vars.searchVar.startPos = pageIndex;
                            // 执行搜索
                            Biz.fn.getStorageCloudList();
                        }
                    });
                },
                //复选框全选
                checkAll:function(){
                    YBA.Plugin.checkAll({
                        allObj:Biz.el.jallObj,
                        eachObj:$(".j-checkEach"),
                        list:$("#j-list")
                    })
                },
                //新增云存储
                addStorageCloud: function(){
                    Biz.el.jaddStorageCloud.bind("click", function(){
                        Biz.fn.storageCloudForm();
                    });
                },
                //管理云存储
                storageCloudAdmin:function(){
                    Biz.el.jlist.delegate(".j-admin", "click", function(){
                        var t = $(this), tr = t.closest("tr"), id = tr.attr("data-id");
                        Biz.fn.getStorageCloudDetail(id, function(data){
                            Biz.fn.storageCloudForm(data);
                        });
                    });
                },
                // 批量删除
                deleteStorageCloud: function(){
                    Biz.el.jdeleteStorageCloud.bind("click", function(){
                        var idStr = "";
                        var data = {};
                        $(".j-checkEach").each(function(){
                            var t = $(this);
                            if(t.is(':checked')){
                                var tr = t.closest("tr"), id = tr.attr("data-id");
                                if(idStr == ""){
                                    idStr = id
                                }else{
                                    idStr = idStr+","+id;
                                }
                            }
                        });
                        if(idStr == ""){
                            YBA.Plugin.msgtip({type: "i", msg: "没有选中项！"})
                            return false;
                        }
                        data = {
                            "ids":idStr
                        }
                        Biz.fn.deleteStorageCloud(data);
                    });
                },
            }
        };

        Biz.init();

        return Biz;
    }
});
